package com.dfec.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class WangEditorImgUpload
 */

@WebServlet(description = "富文本图片上传", urlPatterns = { "/WangEditorImgUpload" })
@MultipartConfig(location = "C://",//文件存放路径，指定的目录必须存在，否则会抛异常  
 maxFileSize = 1024*1024*1024,//最大上传文件大小,经测试应该是字节为单位  
 fileSizeThreshold = 1024*1024*50,//当数据量大于该值时，内容将被写入文件。（specification中的解释的大概意思，不知道是不是指Buffer size），大小也是已字节单位  
 maxRequestSize =  1024*1024*1024 //针对该 multipart/form-data 请求的最大数量，默认值为 -1，表示没有限制。以字节为单位。 
)
public class HtmlloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String fileNameExtractorRegex = "filename=\".+\"";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HtmlloadFile() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	        
	        List<String> fileNames = new LinkedList<String>();  
	        
	        Part part=request.getPart("myFileName");
				//遍历所有的表单内容，将表单中的文件写入上传文件目录  
	            //从Part的content-disposition中提取上传文件的文件名  
	            String fileName = getFileName(part);  
	            if(fileName!=null){  
	                fileNames.add(fileName);  
	            }  
	            
	                System.out.println("http://"+request.getLocalAddr()+":"+request.getLocalPort()+request.getContextPath() + "/uploadfiles/" + fileName);
	        response.getWriter().write("../uploadfiles/" + fileName);
	}
	 /** 
     * 从Part的Header信息中提取上传文件的文件名 
     * @param part 
     * @return  上传文件的文件名，如果如果没有则返回null 
     */  
	  private String getFileName(Part part){  
          //获取header信息中的content-disposition，如果为文件，则可以从其中提取出文件名  
          String cotentDesc = part.getHeader("content-disposition");  
          
          
          String fileName = null;  
          Pattern pattern = Pattern.compile(fileNameExtractorRegex);  
          Matcher matcher = pattern.matcher(cotentDesc);  
          if(matcher.find()){  
              fileName = matcher.group();  
              fileName = fileName.substring(10, fileName.length()-1);  
          }  
          fileName= System.currentTimeMillis()+"."+fileName.split("\\.")[1];
          String realPath = getServletContext().getRealPath("/uploadfiles") + "/" +fileName;
//	        // 将文件写入指定路径下
          
	        try {
				part.write(realPath);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          return fileName;  
      }  

}
